package com.eyaomall.wxmall.common.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.eyaomall.wxmall.model.pojo.ReqPay;
import com.lycheeframework.core.common.util.encrypt.MD5;

public class XmlUtils {

	public static String createXml(Object obj) {
		StringBuilder stringBuilder = new StringBuilder("<xml>");

		Class<?> clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			try {
				PropertyDescriptor pd = new PropertyDescriptor(field.getName(), ReqPay.class);
				Method getMethod = pd.getReadMethod();
				Object o = getMethod.invoke(obj);

				if (o == null)
					continue;

				stringBuilder.append("<" + field.getName() + ">");
				stringBuilder.append(String.valueOf(o));
				stringBuilder.append("</" + field.getName() + ">");

			} catch (Exception e) {
				// ...
			}
		}

		stringBuilder.append("</xml>");

		return stringBuilder.toString();
	}

	/**
	 * 读取文件名
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public static Map<String,String> read(String text) {
		try {
			Document document = (Document) DocumentHelper.parseText(text);
			Element root = document.getRootElement();
			
			//遍历  
	        return listNodes(root);  
		} catch (DocumentException e) {
			//
		}
		
		return null;
	}
	
	 //遍历当前节点下的所有节点  
    @SuppressWarnings("unchecked")
	private static Map<String,String> listNodes(Element node){  
    	Map<String,String> value = new TreeMap<String,String>();
    	
        //如果当前节点内容不为空，则输出  
        if(!(node.getTextTrim().equals(""))){  
            value.put(node.getName(),node.getText());    
        }  
        
        //同时迭代当前节点下面的所有子节点  
        //使用递归  
        Iterator<Element> iterator = node.elementIterator();  
        while(iterator.hasNext()){  
            Element e = iterator.next();  
            value.putAll(listNodes(e));  
        }  
        
        return value;
    }  
    
    /**
     * 校验支付回调报文是否被篡改
     * @param text
     * @param key
     * @return
     */
    public static boolean validResult(String text,String key){
    	Map<String, String> xml = XmlUtils.read(text);
    	
    	Set<String> keySet = xml.keySet();
		String sign = xml.get("sign");
		xml.remove("sign");
		
		StringBuilder builder = new StringBuilder();
		for(String str:keySet){
			builder.append(str);
			builder.append("=");
			builder.append(xml.get(str));
			builder.append("&");
		}
		builder.append("key=" + key);
		
		return MD5.encryptMD5(builder.toString()).toUpperCase().equalsIgnoreCase(sign);
    }

	public static void main(String[] args) throws Exception {
		Map<String, String> data = read("/Users/pro/Downloads/test.xml");
		Set<String> keySet = data.keySet();
		for(String key:keySet){
			System.out.println(key);
		}
	}

}
